package com.letv.android.client.webview;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;

import com.letv.core.utils.LogInfo;
import com.letv.core.utils.NetworkUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by liuxx on 14/12/11.
 * 网络切换监听器
 * 0.获取旧状态
 * 1.判断目前网络状态是否等于旧状态
 * 2.如果不等于则通知H5
 * 此监听器应监听WebView使用的全过程
 * <p>
 * {
 * result : 200 {int} 监听切换成功,
 * pre：'' 2G|3G|4G|wifi|unknown|none {string},
 * now:'' 2G|3G|4G|wifi|unknown|none {string}
 * }
 */
public class NetWorkBroadcastReceiver extends BroadcastReceiver {
    private static List<NetWorkChangeObserver> netWorkChangeObservers = new ArrayList<NetWorkChangeObserver>();

    public synchronized static void registerObserver(NetWorkChangeObserver observer) {
        if (!netWorkChangeObservers.contains(observer)) {
            netWorkChangeObservers.add(observer);
        }
    }

    public synchronized static void unRegisterObserver(NetWorkChangeObserver observer) {
        if (netWorkChangeObservers.contains(observer)) {
            netWorkChangeObservers.remove(observer);
        }
    }

    public void notifyAllObservers(HashMap<String, Object> netMap) {
        for (NetWorkChangeObserver observer : netWorkChangeObservers) {
            observer.onNetTypeChange(netMap);
        }
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {// 监听网络连接状态变化
            LogInfo.log("lxx", "NetWorkBroadcastReceiver onReceive CONNECTIVITY_ACTION");
            int oldNetType = LetvBaseWebViewActivity.netType;
            int currentNetType = NetworkUtils.getNetworkType(context);
            if (oldNetType == -1) {
                LogInfo.log("lxx", "oldNetType为空！BaseWebView初始化有问题！");
            } else if (oldNetType != currentNetType) {
                HashMap<String, Object> netMap = new HashMap<String, Object>();
                netMap.put("pre", NetworkUtils.netTypeToString(oldNetType));
                netMap.put("now", NetworkUtils.netTypeToString(currentNetType));
                netMap.put("result", 200);
                notifyAllObservers(netMap);
                LetvBaseWebViewActivity.netType = currentNetType;
            }
        }
    }
}
